<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Draggable Shape</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="500" height="500"></canvas>

    <script>
        const canvas = document.getElementById('myCanvas');
        const ctx = canvas.getContext('2d');

        // 矩形的初始位置和大小
        let rect = {
            x: 50,
            y: 50,
            width: 100,
            height: 100,
            color: 'blue'
        };

        let dragging = false;
        let offsetX, offsetY;

        // 绘制矩形
        function drawRect() {
            ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除canvas
            ctx.fillStyle = rect.color;
            ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
        }

        // 判断鼠标是否点击在矩形内
        function isMouseInRect(mouseX, mouseY) {
            return mouseX > rect.x && mouseX < rect.x + rect.width && mouseY > rect.y && mouseY < rect.y + rect.height;
        }

        // 获取鼠标在canvas中的位置
        function getMousePos(event) {
            const rect = canvas.getBoundingClientRect();
            return {
                x: event.clientX - rect.left,
                y: event.clientY - rect.top
            };
        }

        // 鼠标按下事件
        canvas.addEventListener('mousedown', (event) => {
            const mousePos = getMousePos(event);
            if (isMouseInRect(mousePos.x, mousePos.y)) {
                dragging = true;
                event.dragging = true;
                offsetX = mousePos.x - rect.x;
                offsetY = mousePos.y - rect.y;
            }
        });

        // 鼠标移动事件
        canvas.addEventListener('mousemove', (event) => {
            if (dragging) {
                const mousePos = getMousePos(event);
                rect.x = mousePos.x - offsetX;
                rect.y = mousePos.y - offsetY;
                drawRect();
            }
        });

        // 鼠标松开事件
        canvas.addEventListener('mouseup', () => {
            dragging = false;
        });

        // 初始化绘制
        drawRect();
    </script>
</body>
</html>
